/**
 * Copyright (c) 2011 eelpo.com
 * All rights reserved.
 */
package com.eelpo.cmmp.core.wicket.application.authorization;

import com.eelpo.cmmp.core.wicket.page.basic.DeniedPage;
import com.eelpo.cmmp.core.wicket.session.CMMPSession;

import org.apache.wicket.Component;
import org.apache.wicket.Page;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.authorization.Action;
import org.apache.wicket.authorization.IAuthorizationStrategy;

/**
 * <pre>
 * 
 * 页面鉴权和授权策略类
 * 
 * </pre>
 * 
 * @author <a href="mailto:Brian@eelpo.com">汪洪州</a>
 * @since 1.0
 */
public class CMMPAuthorizationStrategy implements IAuthorizationStrategy {

	/**
	 * 登录成功之后跳转的页面
	 */
	private Class<? extends Page> loginPage;

	public Class<? extends Page> getLoginPage() {
		return loginPage;
	}

	public void setLoginPage(Class<? extends Page> loginPage) {
		this.loginPage = loginPage;
	}

	@Override
	public boolean isActionAuthorized(Component component, Action action) {
		return true;
	}

	@Override
	public <T extends Component> boolean isInstantiationAuthorized(Class<T> componentClass) {

		if (instanceOf(componentClass, DeniedPage.class)) {
			return isPageAuthorized(componentClass);
		}

		return true;
	}

	protected boolean instanceOf(final Class<?> type, final Class<?> superType) {
		return superType.isAssignableFrom(type);
	}

	protected <T extends Component> boolean isPageAuthorized(Class<T> pageClass) {
		if (CMMPSession.get().isAuthorized()) {
			return true;
		}
		throw new RestartResponseException(loginPage);
	}
}
